package nju.software.tagmanager.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import nju.software.tagmanager.common.constant.MessageConstant;
import nju.software.tagmanager.common.context.BaseContext;
import nju.software.tagmanager.common.exception.TagAlreadyExistsException;
import nju.software.tagmanager.common.result.Result;
import nju.software.tagmanager.pojo.dto.ItemPageQueryDTO;
import nju.software.tagmanager.pojo.entity.Item;
import nju.software.tagmanager.pojo.entity.RelTagItem;
import nju.software.tagmanager.pojo.entity.Tag;
import nju.software.tagmanager.pojo.vo.ItemVO;
import nju.software.tagmanager.service.ItemService;
import nju.software.tagmanager.service.RelTagItemService;
import nju.software.tagmanager.service.TagService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: raychou
 * @date: 2024-01-17 14:26
 * @description:
 */
@Api(tags = "标签实体模块接口")
@RestController
@RequestMapping("/tag-item")
@Slf4j
public class TagItemController {
    @Resource
    private TagService tagService;

    @Resource
    private ItemService itemService;

    @Resource
    private RelTagItemService relTagItemService;


    @ApiOperation("分页查询实体")
    @PostMapping("/item-list")
    public Result<JSONObject> tagList(@RequestBody ItemPageQueryDTO query) {
        IPage<ItemVO> result = itemService.search(query);
        JSONObject data = new JSONObject();
        data.put("total", result.getTotal());
        data.put("records", result.getRecords());
        return Result.success("查询标签成功", data);
    }

    @ApiOperation("添加标签")
    @PostMapping("/add-tag")
    public Result<Object> addTag(@RequestParam("tagName") String tagName) {

        List<Tag> exists = tagService.list(new QueryWrapper<Tag>().eq("name", tagName));
        if (exists != null && !exists.isEmpty()) {
            throw new TagAlreadyExistsException();
        }

        Tag tag = Tag.builder()
                .name(tagName)
                .createUserId(BaseContext.getCurrentUserId())
                .build();

        tagService.save(tag);
        return Result.success(MessageConstant.TAG_INSERT_SUCCESS, null);
    }

    @ApiOperation("根据id删除标签，并级联删除只从属于它的实体")
    @PostMapping("/delete-tag-cascade-by-id")
    public Result<Object> deleteTagCascade(@RequestParam("tagId") Integer tagId) {
        tagService.deleteCascadeById(tagId);
        return Result.success(MessageConstant.DELETE_SUCCESS, null);
    }
    @ApiOperation("找到只从属于特定标签的实体")
    @PostMapping("/find-items-only-following")
    public Result<List<ItemVO>> findItemsOnlyFollowing(@RequestParam("tagId") Integer tagId) {
        List<ItemVO> items = itemService.findOnlyFollowing(tagId);
        return Result.success("查询成功", items);
    }

    @ApiOperation("根据实体id更新备注")
    @PostMapping("/update-comment-by-item-id")
    public Result<Object> updateCommentByItemId(@RequestParam("itemId") Integer itemId,
                                               @RequestParam("comment") String comment) {
        Item item = Item.builder()
                .id(itemId)
                .comment(comment)
                .build();
        itemService.updateById(item);
        return Result.success(MessageConstant.COMMENT_UPDATE_SUCCESS, null);
    }


    @ApiOperation("将指定实体加入指定标签")
    @PostMapping("/add-item-to-tag")
    public Result<Object> addItemToTag(@RequestParam("itemId") Integer itemId,
                                       @RequestParam("tagId") Integer tagId) {
        relTagItemService.addItemToTag(itemId, tagId);
        return Result.success("标签加入类别成功");
    }

    @ApiOperation("根据标签名找到所有匹配的标签")
    @PostMapping("/find-items-by-name")
    public Result<List<Item>> findTagsByName(@RequestParam("itemName") String itemName) {
        return Result.success(itemService.list(new QueryWrapper<Item>().like("name", itemName)));
    }

    @ApiOperation("将指定实体从指定标签中删除")
    @PostMapping("/remove-item-from-tag")
    public Result<Object> removeItemFromTag(@RequestParam("itemId") Integer itemId, @RequestParam("tagId") Integer tagId) {
        boolean removed = relTagItemService.remove(new QueryWrapper<RelTagItem>()
                .eq("item_id", itemId)
                .eq("tag_id", tagId));

        if (!removed) {
            log.error("删除失败:{ itemId:{}, tagId:{} }", itemId, tagId);
            return Result.error(MessageConstant.DELETE_FAILURE);
        }
        return Result.success(MessageConstant.DELETE_SUCCESS, null);
    }

    @ApiOperation("删除实体")
    @PostMapping("/delete-item-by-id")
    public Result<Object> deleteItemById(@RequestParam("itemId") Integer itemId) {
        itemService.deleteById(itemId);
        return Result.success(MessageConstant.DELETE_SUCCESS, null);
    }

    @ApiOperation("新增实体并加入指定标签")
    @PostMapping("/add-new-item-by-tag-id")
    public Result<Object> addNewItemByTagId(@RequestParam("itemName") String itemName,
                                            @RequestParam("tagId") Integer tagId) {
        itemService.addItemByTagId(itemName, tagId);
        return Result.success("新增标签并加入类别成功");
    }

}
